package com.glela.common;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.DateUtil;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.request.RequestVersionModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseVersion;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.VersionService;

public class CommonLogInterceptors extends HandlerInterceptorAdapter {
	private static Logger logger = LoggerFactory.getLogger(CommonLogInterceptors.class);
	
	public Long actionBeginTime = 0l;
	String url = null ;
	List<String> oldUrlList = new ArrayList<String>();
	
	@Autowired
	private BaseRestrictionsService  baseRestrictionsService;
	@Autowired
	private VersionService versionService;
	
	private static long requestCount = 1 ;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		requestCount++;
		
		boolean res = true;
		
		response.setCharacterEncoding("UTF-8");  
		response.setContentType("application/json; charset=utf-8"); 
		oldUrlList.add("/advertisement/selectAdvertisement");
		oldUrlList.add("/version/getVersionInfo");
		oldUrlList.add("/version/testgetVersionInfo");
		oldUrlList.add("/version/testgetVersionInfo2");
		actionBeginTime = new Date().getTime();
		url = request.getServletPath();
		
		
		Map<String,Object> fiterMap = LocalCache.localCache.get(LocalCache.FILTER_URL_ONE);
		if(fiterMap != null && fiterMap.size() > 0) {
			if(fiterMap.containsKey(url)) {
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("code", 99996);
				map.put("message", "");
				Integer isMessage = fiterMap.get(url) == null ? 0 : Integer.parseInt((String)fiterMap.get(url));
				if(isMessage > 0) {
					map.put("message", "目前双十一访问人数过多,该功能暂不支持访问，稍后开放!");
				}
				Object ps = JSONObject.toJSON(map);
				PrintWriter writer = response.getWriter();
				writer.append(ps.toString());
				writer.close();
				return false;
			}
			
		}
				
		if(oldUrlList.contains(url)){
			//跳过强制版本校验
 			return true;
  		}
		
		
		
		//按一定比例丢弃
//		Map<String,Object> _SYS_DISCARD_MAP = (Map<String,Object>)LocalCache.localCache.get(LocalCache.SYS_DISCARD_NUMBER_KEY);
//		BaseRestrictions sys_discard_number = _SYS_DISCARD_MAP == null ? null : (BaseRestrictions)_SYS_DISCARD_MAP.get(LocalCache.SYS_DISCARD_NUMBER_KEY);
//			if(sys_discard_number == null) {
//				sys_discard_number = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.SYS_DISCARD_NUMBER_KEY);
//				if(sys_discard_number != null) {
//				Map<String,Object> sys_discard_number_map = new HashMap<String , Object>();
//				sys_discard_number_map.put(LocalCache.SYS_DISCARD_NUMBER_KEY, sys_discard_number);
//				LocalCache.localCache.setKey(LocalCache.SYS_DISCARD_NUMBER_KEY, sys_discard_number_map);
//			}
//		}
//		if(sys_discard_number != null && sys_discard_number.getExperience() > 0) {
//			//进行拦截处理
//			if(requestCount / sys_discard_number.getExperience() == 0) {
//				Map<String,Object> map = new HashMap<String,Object>();
//				map.put("code", 99996);
//				map.put("message", "当前活动太火爆, 宝宝请再试一次！");
//				Object ps = JSONObject.toJSON(map);
//				PrintWriter writer = response.getWriter();
//				writer.append(ps.toString());
//				writer.close();
//				return false;
//			}
//			
//		}
		
		
		
		//系统维护开关  
		Map<String,Object> _SYS_OPEN_STATUS_MAP = (Map<String,Object>)LocalCache.localCache.get(LocalCache.SYS_OPEN_STATUS);
		BaseRestrictions checkSystemOpenStatus = _SYS_OPEN_STATUS_MAP == null ? null : (BaseRestrictions)_SYS_OPEN_STATUS_MAP.get(LocalCache.SYS_OPEN_STATUS);
		if(checkSystemOpenStatus == null) {
			checkSystemOpenStatus = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.SYS_OPEN_STATUS);
			Map<String,Object> sys_open_status_map = new HashMap<String , Object>();
			sys_open_status_map.put(LocalCache.SYS_OPEN_STATUS, checkSystemOpenStatus);
			LocalCache.localCache.setKey(LocalCache.SYS_OPEN_STATUS, sys_open_status_map);
		}
		
		//双十一设置为 1 ， 系统正常访问
		if(checkSystemOpenStatus != null && checkSystemOpenStatus.getExperience() == 0) {
			BaseRestrictions sysopenDateTime = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.SYS_PLAN_OPEN_DATE);
			Map<String,String> returnMap = new HashMap<String,String>();
			returnMap.put("systemMsg", "预计系统恢复时间为 ");
			returnMap.put("systemOpenTime", sysopenDateTime.getName());
			Object ps = JSONObject.toJSON(new ResponseResultModel<Object>(ErrorEnum.C99998,returnMap));
			PrintWriter writer = response.getWriter();
			writer.append(ps.toString());
			writer.close();
			return false;
		}
		
		
		//版本检查 0 不检查   1 强制检查， 平时为了系统效率可以设置为 0 ，系统升级期间可修改为 1
		Map<String,Object> _map = (Map<String,Object>)LocalCache.localCache.get(LocalCache.SYS_FORCE_UPDATE_CHECK_OFF);
		BaseRestrictions checkBaseRestrictions =  _map == null ? null : (BaseRestrictions)_map.get(LocalCache.SYS_FORCE_UPDATE_CHECK_OFF);
		if(checkBaseRestrictions == null) {
			 checkBaseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.SYS_FORCE_UPDATE_CHECK_OFF);
			 Map<String , Object> addMap = new HashMap<String , Object>();
			 addMap.put(LocalCache.SYS_FORCE_UPDATE_CHECK_OFF, checkBaseRestrictions);
			 LocalCache.localCache.setKey(LocalCache.SYS_FORCE_UPDATE_CHECK_OFF, addMap);
		}
		
		
		//重大活动节日期间可设置为 0 
		if(checkBaseRestrictions != null && checkBaseRestrictions.getExperience() == 1)  { // 0 不打开强制更新检查 , 1 打开强制更新检查
			String phoneType = request.getHeader("phoneType");
			String appSystemVersion = request.getHeader("appSystemVersion");
			if(!StringUtils.isBlank(phoneType) && !StringUtils.isBlank(appSystemVersion)) {
				phoneType = phoneType.toLowerCase();
				RequestVersionModel req = new RequestVersionModel();
				req.setVersionType("app");
				req.setInterfaceVersion("v2.0");
				req.setVersionCode(appSystemVersion);
				if(CommonConstants.PHONE_CLIENT_IOS.equals(phoneType)) {
					req.setType(2);
					ResponseVersion rep = versionService.getVersionInfov2(req);
					
					if(rep.getForcedUpdate() == 1) {
						//ResponseBaseModel error = new ResponseBaseModel(99997," 当前版本号： " + appSystemVersion + "  小于当前系统最低版本号: " + rep.getLatestBuildCode() + "请进行升级后进行操作, 感谢支持! ");
						Object ps = JSONObject.toJSON(new ResponseResultModel<Object>(ErrorEnum.C99997,rep));
						PrintWriter writer = response.getWriter();
						writer.append(ps.toString());
						writer.close();
						return false;
					}
					
					
				}else if(CommonConstants.PHONE_CLIENT_ANDROID.equals(phoneType)) {
					req.setType(1);
					ResponseVersion rep = versionService.getVersionInfov2(req);
					if(rep.getForcedUpdate() == 1) {
						res = false;
						//ResponseBaseModel error = new ResponseBaseModel(99997," 当前版本号： " + appSystemVersion + "  小于当前系统最低版本号: " + rep.getLatestBuildCode() + "请进行升级后进行操作, 感谢支持! ");
						Object ps = JSONObject.toJSON(new ResponseResultModel<Object>(ErrorEnum.C99997,rep));
						PrintWriter writer = response.getWriter();
						writer.append(ps.toString());
						writer.close();
					}
				}
			}
		}
		
	   if(requestCount > 900000000) {
		   requestCount = 1;
	   }
		
	   return res;
	}
	
	
	
	/***
	 * 
	 * 全局日志记录，暂时用来处理服务端记录用户行为，存储为 格式文本
	 * 
	 * 
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}
	
	
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if (logger.isDebugEnabled()) {
			StringBuilder builder = new StringBuilder();
			BufferedReader br = request.getReader();
			//计算请求相应时间 （单位：毫秒）
			Long actionTime = new Date().getTime() - actionBeginTime;
			String dateTime = DateUtil.currentYourDate("yyyy-MM-dd HH:mm:ss");
			//获取参数
			String str;
			while ((str = br.readLine()) != null) {
				builder = builder.append(str);
			}
			url = request.getServletPath();
			//GET HEAD COMMON PARAM
			//String token = request.getHeader("userToken");
			String machineCode = request.getHeader("machineCode"); //机器码
			String phoneType = request.getHeader("phoneType");//手机客户端类型
			String brand = request.getHeader("brand");//手机厂商
			String phoneSystemVersionCode = request.getHeader("phoneSystemVersionCode");//手机系统版本
			String appSystemVersion = request.getHeader("appSystemVersion");//APP当前版本
			String phoneModel = request.getHeader("phoneModel"); //手机号型号

			//logger.info(":::::::::::::::>>>> 请求客户端信息:\n 机器码: " + machineCode + "\n 客户端手机客户端类型：" + phoneType + "\n 手机品牌: " + brand + "\n 客户端手机系统版本：" + phoneSystemVersionCode + "\n APP当前版本号: " + appSystemVersion + "\n 手机型号: " + phoneModel);
			//logger.info(dateTime + "--------" + actionTime + "------------" + url + "-------" + builder.toString());
		}
	} 
	
}
